<template>
  <el-dialog
    v-el-drag-dialog
    :title="'商品模式新增调价'"
    :visible.sync="visible"
    width="80%"
    @closed="reset"
  >

    <el-table-form ref="dataForm" class="form" :model="shop" label-position="right" label-width="80px">
      <el-form-item label="商品分类" prop="orgSNNo">
        <el-tree-select
          v-model="shop.gtId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择商品分类',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: goodsTreeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="商品名称" class="merge-item">
        <el-select v-model="shop.goodsId" style="width: 170px; margin-right: 2px;">
          <el-option v-for="(l,i) in goodsTypesDetailList" :key="i" :value="l.goodsId" :label="l.goodsName" />
        </el-select>
      </el-form-item>
      <el-form-item label="生效机构" prop="orgSNNo">
        <el-tree-select
          v-model="shop.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: orgTreeData
          }"
          @node-click="selectOrgTreeChange1"
        />
      </el-form-item>
      <el-form-item label="波动方式" class="merge-item">
        <el-select v-model="shop.priceType" style="width: 170px; margin-right: 2px;">
          <el-option v-for="(l,i) in priceTypeMap" :key="i" :value="l.value" :label="l.desc" />
        </el-select>
      </el-form-item>
      <el-form-item label="波动价格" class="merge-item">
        <el-input v-model="shop.price" clearable placeholder="请输入" />
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div class="page_main">
      <div class="left">
        <div class="info-title">
          <span class="title-icon" />
          <span>商品现有报价客户</span>
        </div>
        <lb-table
          ref="lbTable_left"
          v-loading="$loadingPlugin.fetchData"
          border
          element-loading-text="加载中"
          :column="tableDataLeft.column"
          :data="tableDataLeft.data"
          highlight-current-row
          :total="tableDataLeft.total"
          pagination
          height="500"
          @current-change="selectLeftTable"
          @fetch="fetchDataLeft"
        />
      </div>
      <div class="right">
        <div class="info-title">
          <span class="title-icon" />
          <span>客户信息</span>
        </div>
        <div class="border">
          <!-- <p>11111</p> -->
          <el-form ref="dataForm" style="height: 30px;" class="form" :model="cmsInfo" label-position="right" label-width="80px">
            <el-form-item label-width="0" prop="csmPhone">
              <el-input v-model="cmsInfo.text" size="mini" placeholder="请输入">
                <el-select slot="prepend" v-model="cmsInfo.type" size="mini" style="width: 100px;" placeholder="请选择">
                  <el-option label="客户电话" :value="'csmRgPhone'" />
                  <el-option label="客户编号" :value="'csmCode'" />
                </el-select>
                <el-button slot="append" size="mini" class="append-search" @click="searchCms">查询</el-button>
              </el-input>
            </el-form-item>
          </el-form>
          <p style="display: flex; align-items: center; margin-top: 10px;">
            <span class="info" style="width: 33%;">客户编号：{{ cmsInfo.csmCode }}  </span>
            <span class="info" style="width: 33%;">客户名称：{{ cmsInfo.csmName }}  </span>
            <span class="info" style="width: 33%;">客户电话：
              <el-select slot="prepend" v-model="cmsInfo.csmRgPhone" size="mini" style="width: 150px;" placeholder="请选择">
                <el-option v-for="(l,i) in cmsInfo.phoneItems" :key="i" :label="l.csmPhone" :value="l.csmPhone" />
              </el-select>  </span>
          </p>
          <p style="display: flex; margin-top: 10px;">
            <span class="info" style="width: 33%;">客户类型: {{ cmsInfo.csmType }}   </span>
            <span class="info" style="width: 66%;">所属机构：{{ cmsInfo.nearStationName }}   </span>
          </p>
          <p style="display: flex; margin-top: 10px;">
            <span class="info" style="width: 90%;">客户地址：
              <el-select slot="prepend" v-model="cmsInfo.csmRgAddress" size="mini" style="width: 80%;" placeholder="请选择">
                <el-option v-for="(l,i) in cmsInfo['addressItems']" :key="i" :label="l.csmAddress" :value="l.csmAddress" />
              </el-select>
            </span>
            <el-button size="mini" type="primary" @click="addUser">确认添加</el-button>
          </p>
        </div>
        <div class="border" style="width: 100%; margin-top: 10px;">
          <p>添加客户</p>
          <lb-table
            ref="tableData_right"
            v-loading="$loadingPlugin.fetchData"
            border
            stripe
            element-loading-text="加载中"
            :column="tableDataRight.column"
            :data="tableDataRight.data"
            highlight-current-row
            :total="tableDataRight.total"
            custom-column
            height="200"
          />
          <el-form label-width="90px;" style="margin-top: 10px;">
            <el-form-item label-width="90px" style="width: 100%;" label="时效范围:" class="merge-item">
              <el-date-picker
                v-model="submit.date"
                style="width: 100%;"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label-width="90px" style="width: 100%;" label="生效机构:" prop="orgSNNo">
              <el-tree-select
                v-model="submit.orgSNNo"
                :clearable="false"
                class="tree-select"
                :popover-width="360"
                :select-params="{
                  clearable: true,
                  placeholder: '请选择组织机构',
                  loading: $loadingPlugin.getTreeData
                }"
                :tree-params=" {
                  'default-expand-all': true,
                  'expand-on-click-node': false,
                  'highlight-current': true,
                  props:{
                    value:'orgSNNo',
                    label: 'orgName',
                    disabled: 'disabled',
                  },
                  data: orgTreeData
                }"
                @node-click="selectOrgTreeChange"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { parseTime } from '@/utils'
  import { goodsTypeDetail, CmsSpecialPriInfo, CmsSpecialDeleteGoods, CmsSpecialSearchCsmInfo, CmsSpecialconfigSave } from '@/api'
  export default {
    name: 'addSelectPrice',
    props: ['orgTreeData', 'goodsTreeData'],
    data() {
      return {
        visible: false,
        goodsTypesDetailList: [],
        disAbledStatu: true,
        selectOrgValue: {}, // 生效机构
        cmsInfo: {
          type: 'csmRgPhone',
          phoneItems: [],
          addressItems: []
        },
        shop: {

        },
        submit: {
          date: [],
          orgSNNo: null
        },
        priceTypeMap: [{ 'value': 1, 'desc': '下浮', 'key': 'Fluctuating' }, { 'value': 2, 'desc': '固定', 'key': 'Fixed' }],

        tableDataLeft: {
          data: [],
          column: [
            { label: '状态', prop: 'checkStatus', width: 80, align: 'center',
              render: (h, { row, column }) => <span>{this.statusMap(row, column) }</span>
            },
            { label: '时效范围', prop: 'startDt', width: 180, align: 'center',
              render: (h, { row, column }) => <span>{this.timeformat(row, column) }</span>
            },
            { label: '波动方式', prop: 'priceType', width: 80, align: 'center',
              render: (h, { row }) => <span>{row.priceType && this.priceTypeMap.find(l => l.value === row.priceType).desc }</span>
            },
            { label: '波动价格', prop: 'price', width: 80, align: 'right' },
            { label: '客户名称', prop: 'csmName', width: 80, align: 'center' },
            { label: '客户编号', prop: 'csmCode', width: 80, align: 'center' },
            { label: '客户电话', prop: 'contactPhone', width: 100, align: 'center' },
            { label: '客户地址', prop: 'csmAddress', width: 180, align: 'center' },
            { label: '生效机构', prop: 'scopeOrgName', width: 180, align: 'center' },
            { label: '操作', prop: 'op', width: 150, align: 'center',
              render: (h, { row, column, $index }) => <span onClick={() => { this.delShop(row, $index) }} style='color:red;cursor: pointer'>删除</span>
            }
          ]
        },
        tableDataRight: {
          total: 0,
          column: [
            { label: '操作', prop: 'op', width: 99, align: 'center',
              render: (h, { row, column, $index }) => <span onClick={() => { this.delCms(row, $index) }} style='color:red;cursor: pointer'>删除</span>
            },
            { label: '客户编号', prop: 'csmCode', width: 80, align: 'center' },
            { label: '客户名称', prop: 'csmName', width: 123, align: 'center' },
            { label: '客户类型', prop: 'csmType', width: 80, align: 'center' },
            { label: '电话', prop: 'csmRgPhone', width: 140, align: 'center' },
            { label: '所属机构', prop: 'csmOrg', width: 100, align: 'center' },
            { label: '地址', prop: 'csmRgAddress', width: 200, align: 'center' }

          ],
          data: []
        }
      }
    },
    methods: {
      async search() {
        // console.log(this.shop)
        // try {
        //   var params = { ...this.shop }
        //   var res = await CmsSpecialPriceOriented(params)
        //   console.log(res)
        // } catch (e) {
        //   console.log(e)
        // }
        this.fetchDataLeft({})
      },
      // 查询客户信息

      async fetchDataLeft({ pageIndex = 1, pageSize = 0 }, data) {
        if (JSON.stringify(this.shop) === '{}') {
          return
        }
        // 校验商品分类
        if (!this.shop.gtId) {
          this.$message.error('请选择商品分类')
          return
        }

        // 校验商品名称
        if (!this.shop.goodsId) {
          this.$message.error('请选择商品名称')
          return
        }

        // 校验波动方式
        if (!this.shop.priceType) {
          this.$message.error('请选择波动方式')
          return
        }

        // 校验价格
        var price = this.shop.price
        if (!price) {
          this.$message.error('请输入波动价格')
          return
        } else {
          var reg = /^-?\d+(,\d{3})*(\.\d{1,2})?$/
          if (reg.test(price) && price > 0) {
            11
          } else {
            this.$message.error('波动价格输入有误，请重新输入')
            return
          }
        }
        const params = {
          ...this.shop,
          pageIndex,
          pageSize
        }
        const res = await CmsSpecialPriInfo(params)
        this.tableDataLeft.data = res.data.rows
        this.tableDataLeft.total = res.data.total
      },
      // async fetchDataRight({ pageIndex = 1, pageSize = 0 }, data) {
      //   if (JSON.stringify(this.shop) === '{}') {
      //     return
      //   }
      //   const params = {
      //     ...data,
      //     pageIndex,
      //     pageSize
      //   }
      //   const res = await CmsSpecialPriInfo(params)
      //   this.tableDataRight.data = res.data.rows
      //   this.tableDataRight.total = res.data.total
      // },
      selectLeftTable(val) {
        // console.log(val, 'val')
        // const params = { 'goodsId': val.goodsId, 'priceType': val.priceType, 'price': val.price, 'scopeOrgSNNo': val.orgSNNo }
        // if (this.disAbledStatu) params['expired'] = 2
        // this.fetchDataRight({}, params)
      },
      // 选择商品分类
      selectTreeChange(value) {
        // this.orgSNNo = value.orgSNNo
        this.getGoodsTypeDetails(value.gtId)
      },
      // 选择生效机构
      selectOrgTreeChange(value) {
        this.selectOrgValue = { ...value }
        // this.orgSNNo = value.orgSNNo
      },
      selectOrgTreeChange1(value) {
        // this.selectOrgValue = { ...value }
        // this.orgSNNo = value.orgSNNo
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          this.goodsTypesDetailList = res.data.rows
        } catch (error) {
          console.log(error)
        }
      },
      // 状态文本格式化
      statusMap(row, column) {
        if (row.endDt < row.nowDt) {
          return '已失效'
        }
        const val = row[column.property]
        if (val === 0) {
          return '一级待审'
        } else if (val === 1) {
          return '二级待审'
        } else if (val === 2) {
          return '已生效'
        } else if (val === 4) {
          return '已驳回'
        }
        return ''
      },
      // 时间格式化
      timeformat(row, column) {
        const startTime = parseTime(row.startDt, '{y}:{m}:{d} {h}:{i}:{s}')
        const endTime = parseTime(row.endDt, '{y}:{m}:{d} {h}:{i}:{s}')
        return `${startTime}至${endTime}`
      },
      // 查询客户信息
      async searchCms() {
        var phoneReg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        var csmCodeReg = /^\d{1,}$/
        if (this.cmsInfo.type === 'csmRgPhone' && !phoneReg.test(this.cmsInfo.text)) {
          this.$message.error('电话号码格式错误，请重新输入')
          return
        } else if (this.cmsInfo.type === 'csmCode' && !csmCodeReg.test(this.cmsInfo.text)) {
          this.$message.error('客户编号输入错误，请重新输入')
          return
        }
        try {
          const params = {
            csmStatus: 9// 查询状态不是已注销的客户
          }
          params[this.cmsInfo.type] = this.cmsInfo.text
          // var a = this.cmsInfo.text
          const res = await CmsSpecialSearchCsmInfo(params)
          if (res.data) {
            this.cmsInfo = { ...res.data, type: 'csmRgPhone', text: null }
          } else {
            this.$message.error('未获取到客户信息')
          }
        } catch (e) {
          console.log(e)
        }
      },
      // 添加客户（本地）
      addUser() {
        console.log(this.cmsInfo)
        var exists = false // 添加的规格在表格中是否已存在
        var csmCode = this.cmsInfo.csmCode
        for (var i = 0; i < this.tableDataRight.data.length; i++) {
          if (csmCode === this.tableDataRight.data[i].csmCode) {
            exists = true
          }
        }
        if (!exists) {
          var data = {}
          data.isChecked = false // 未选中
          data.csmCode = this.cmsInfo.csmCode // 客户编号
          data.csmName = this.cmsInfo.csmName // 客户名称
          if (!this.cmsInfo.csmCode) {
            this.$message.error('请查询客户')
            return
          }
          data.csmType = this.cmsInfo.csmType // 客户类型
          data.orgSNNo = this.cmsInfo.orgSNNo
          data.contact = this.cmsInfo.contact
          data.csmId = this.cmsInfo.csmId
          data.csmRgPhone = this.cmsInfo.csmRgPhone
          data.csmOrg = this.cmsInfo.nearStationName // 所属机构
          data.csmRgAddress = this.cmsInfo.csmRgAddress // 地址
          // _this.customTable.datagrid('appendRow', data)
          // var index = _this.customTable.datagrid('getRowIndex', data)
          // _this.customTable.datagrid('checkRow', index)
        } else {
          this.$message.error('当前用户已存在,不可重复添加')
          return
        }
        this.tableDataRight.data.push({ ...data })
      },
      // 删除客户（本地）
      delCms(row, index) {
        this.tableDataRight.data.splice(index, 1)
      },
      // 删除商品
      delShop(row) {
        const vm = this
        this.$confirm(`确定要删除吗？`, '提示', {
          type: 'info'
        }).then(() => {
          var params = {
            categoryDetailId: row.categoryDetailId,
            csmId: row.csmId,
            priceCgId: row.priceCgId
          }
          try {
            CmsSpecialDeleteGoods(params).then(data => {
              vm.fetchDataLeft({})
            })
          } catch (e) {
            console.log(e)
          }
        })
      },
      open(params) {
        this.visible = true
      },
      async success() {
        console.log(this.tableDataRight.data, 'table')
        var paramData = {}
        // 校验商品分类
        if (!this.shop.gtId) {
          this.$message.error('请选择商品分类')
          return
        } else {
          paramData.gtId = this.shop.gtId
          paramData.gtName = this.goodsTreeData.find(l => l.gtId === this.shop.gtId).gtName
        }

        // 校验商品名称
        if (!this.shop.goodsId) {
          this.$message.error('请选择商品名称')
          return
        } else {
          paramData.goodsId = this.shop.goodsId
          paramData.goodsName = this.goodsTypesDetailList.find(l => l.goodsId === this.shop.goodsId).goodsName
        }

        // 校验波动方式
        if (!this.shop.priceType) {
          this.$message.error('请选择波动方式')
          return
        } else {
          paramData.priceType = this.shop.priceType
        }

        // 校验价格
        var price = this.shop.price
        if (!price) {
          this.$message.error('请输入波动价格')
          return
        } else {
          var reg = /^-?\d+(,\d{3})*(\.\d{1,2})?$/
          if (reg.test(price) && price > 0) {
            paramData.price = price
          } else {
            this.$message.error('波动价格输入有误，请重新输入')
            return
          }
        }

        // 客户列表数据
        var customerInfoList = []
        var rows = this.tableDataRight.data
        if (!rows.length) {
          this.$message.error('请添加客户')
          return
        } else {
          for (var x = 0; x < rows.length; x++) {
            var row = rows[x]
            var customInfo = {
              csmCode: row.csmCode,
              csmPhone: row.csmRgPhone,
              csmAddress: row.csmRgAddress
            }
            customerInfoList.push(customInfo)
          }
          paramData.customerInfoList = customerInfoList
        }

        // 校验时间
        console.log(this.submit.date)
        if (!this.submit.date.length) {
          this.$message.error('请选择生效时间')
          return
        }
        paramData.startDt = this.submit.date[0]
        paramData.endDt = this.submit.date[1]

        // 校验生效机构
        var selectedOrg = this.selectOrgValue
        if (selectedOrg.orgName) {
          paramData.orgId = selectedOrg.orgId
          paramData.orgName = selectedOrg.orgName
          paramData.orgSNNo = selectedOrg.orgSNNo
        } else {
          this.$message.error('请选择生效机构')
          return
        }
        console.log(paramData)
        // infoList
        const params = {
          detail: paramData,
          infoList: this.tableDataRight.data
        }
        const res = await CmsSpecialconfigSave(params)
        if (res.success) {
          this.$message.success('提交成功')
          this.visible = false
        }
      },
      reset() {

      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    height: 20px;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
.form_right {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 40%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 8px;
  margin-bottom: 10px;
  font-size: 14px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 14px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
.page_main {
  display: flex;
  box-sizing: border-box;
  .left {
    width: 50%;
    padding: 5px;
    // border: 1px solid #ebeff6;
  }
  .right {
    width: 50%;
    padding: 5px;
  }
  .info {
    display: inline-block;
    overflow: hidden;
    font-size: 14px;
    color: #999;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
  }
  .border {
    padding: 15px 5px;
    border: 1px solid #ebeff6;
  }
  p {
    padding: 0;
  }
}
</style>
